package com.woniu.zsd.platform.config;

import com.woniu.zsd.platform.interceptor.AccountLoginInterceptor;
import com.woniu.zsd.platform.interceptor.PermissionInterceptor;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.convert.converter.Converter;
import org.springframework.format.FormatterRegistry;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;

@Configuration
public class WebConfig implements WebMvcConfigurer {
    @Resource
    private PermissionInterceptor permissionInterceptor;
    @Resource
    private AccountLoginInterceptor loginInterceptor;
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**") // 所有接口
                .allowCredentials(true) // 是否发送 Cookie
                .allowedOrigins("*") // 支持域
                .allowedMethods(new String[]{"GET", "POST", "PUT", "DELETE"})
                .allowedHeaders("*")
                .exposedHeaders("*");

    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(loginInterceptor)
                .addPathPatterns("/**") // 所有接口
                .excludePathPatterns("/account/accountLogin")
                .excludePathPatterns("/swagger-resources/**", "/webjars/**", "/v2/**", "/swagger-ui.html/**")
                .excludePathPatterns("/recycleBin/selectRecycleBinByLocation")
                .excludePathPatterns("/recycleBin/selectStationNameByStationId")
                .excludePathPatterns("/recycleBin/updateSiteScoreBySiteId"); // 排除登录、注册、登出接口

        registry.addInterceptor(permissionInterceptor)
                .addPathPatterns("/**") // 所有接口
                .excludePathPatterns("/account/accountLogin")
              .excludePathPatterns("/swagger-resources/**", "/webjars/**", "/v2/**", "/swagger-ui.html/**")
                .excludePathPatterns("/recycleBin/selectRecycleBinByLocation")
                .excludePathPatterns("/recycleBin/selectStationNameByStationId")
                .excludePathPatterns("/recycleBin/updateSiteScoreBySiteId"); // 排除登录、注册、登出接口
    }

    @Override
    public void addFormatters(FormatterRegistry registry) {
        registry.addConverter(new Converter<String, LocalDate>() {
            @Override
            public LocalDate convert(String s) {
                DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
                LocalDate localDate = LocalDate.parse(s, formatter);
                return localDate;
            }
        });
    }
}
